package cn.zj.logistics.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.zj.logistics.pojo.User;
import cn.zj.logistics.pojo.UserExample;
import cn.zj.logistics.pojo.UserExample.Criteria;
import cn.zj.logistics.service.PermissionService;
import cn.zj.logistics.service.UserService;

public class CustomRealm extends AuthorizingRealm{

	
	/*
	 * 开发完成认证逻辑
	 * 
	 */
	
	@Autowired
	private UserService userService;
	
	
	@Autowired
	private PermissionService permissionService;
	
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//获取认证的身份（登录的账号）
		String principal = (String) token.getPrincipal();
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(principal);
		List<User> users = userService.selectByExample(example);
		System.out.println(users);
		
		//账号不存在
		if(users.size() == 0) {
			return null;
		}
		
		//获取登录的用户
		User user = users.get(0);
		//获取密码 : 原密码+盐 md5 加密三次
		String password = user.getPassword();
		//获取salt 
		String salt = user.getSalt();
		
		//创建认证信息对象
		AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, ByteSource.Util.bytes(salt), this.getName());
		
		
		return authenticationInfo;
	}
	
	
	/*
	 * 授权逻辑
	 * 
	 */
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//1.获取认证的身份（User）
		User user = (User) principals.getPrimaryPrincipal();
		
		//2.获取User的对应的角色的权限id ：1,2,3....
		String permissionIds = user.getPermissionIds();
		//3.切割权限字符串并转换成Long类型数组（数据库设置所有的表id都是长整型）
		String[] split = permissionIds.split(",");
		List<Long> permissionIdsList = new ArrayList<>();
		for (String permissionId : split) {
			permissionIdsList.add(Long.valueOf(permissionId));
		}
		System.out.println(permissionIdsList);
		
		//3.调用PermissionService根据权限的id查询出权限表达式的方法（Mapper逆向工程没有，开发者自己写）
		List<String> permissions = permissionService.selectPermissionExpressionByIds(permissionIdsList);
		
		//4.创建授权信息对象
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		//5.将权限表达式设置给授权信息对象
		authorizationInfo.addStringPermissions(permissions);
		
		//6.返回授权信息对象
		return authorizationInfo;
	}
	
	
	
	

}
